import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';
import styles from './../ValveFlowMeterSIte/index.less'
import find from 'lodash/find';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem ,getFileType} from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import MailDetail from './MailDetail';
import ReactDataGrid from 'react-data-grid';
import AddOrEditMeter from './AddOrEdit';
import mail from './../../images/mail.png'
import mailOpen from './../../images/mail-open.png'
const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ safety_article_manage, loading,global }) => ({
  safety_article_manage,
  global,
  loading: loading.models.safety_article_manage,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      safety_article_manage: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        safety_article_manage: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'safety_article_manage/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'safety_article_manage/changeLoaded',
          });
          dispatch({
            type: 'safety_article_manage/changeTableY',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'safety_article_manage/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'safety_article_manage/changeTableY',
    });
  };
  findChildFunc = (cb)=> {
    this.file=cb
  }

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.react-grid-Canvas');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'safety_article_manage/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      safety_article_manage: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label="文章标题">
          {getFieldDecorator('title', {
            initialValue: searchParams.title,
          })(<Input style={{ width: '180px' }} placeholder="请输入"/>)}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  type: searchParams.type,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          {
            find(this.permissions, { name: "safe_article_edit" }) &&
            <Button
              icon="plus"
              style={{ marginLeft: 8 }}
              type="primary"
              onClick={
                () => {
                  this.setState({
                    addModal: true,
                  });
                }
              }
            >
              发布文章
            </Button>
          }

        </FormItem>

      </Form>
    );
  }

  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'safety_article_manage/add',
      payload: {
        ...formValues,
      },
      callback() {
        message.success('添加员工成功');
        that.setState({
          addModal: false,
        });
        const {
          safety_article_manage: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    const {
      safety_article_manage: { searchParams },
    } = this.props;
    this.handleSearch({
      status:'0',
      title:'',
      page: 1,
      per_page: 30,
      type:searchParams.type,
    });
  };

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `safety_article_manage/edit`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改员工成功');
        that.setState({
          editModal: false,
        });
        const {
          safety_article_manage: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `safety_article_manage/remove`,
      payload: { id },
      callback: () => {
        message.success('删除文章成功');
        const {
          safety_article_manage: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  render() {
    const that = this;
    const {
      safety_article_manage: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global:{gridTableW}
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen:true,
        formatter: (event) => {
          const {
            safety_article_manage: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '文章标题',
        frozen:true,
        width: 200,
        key: 'title',
      },
      {
        name: '文章板块',
        frozen:true,
        width: 230,
        key: 'type',
        formatter:(event)=>{
          return event.value.map((item,index)=>{
            const findRes=find( [{id:0,name:'全部板框'},{id:21,name:'首页轮播'},{id:22,name:'安全要闻'},{id:23,name:'政策法规'},{id:24,name:'安全教育'},{id:25,name:'事故通报'},
              {id:26,name:'安全通知'}],function(o){
              return o.id===Number(item)
            })
            if(findRes){
              return <span key={index} style={{background:'#3c67f5',color:'#fff',padding:'2px 5px',marginRight:'5px'}}>{findRes.name}</span>
            }else{
              return  ''
            }
          })

        }
      },
      {
        name: '发布时间',
        width: 160,
        key: 'created_at',
      },
      {
        name: '操作者',
        width: 120,
        key: 'operator_name',
      },
      {
        name: '转载来源',
        width: 120,
        key: 'reprinted_source',
      },
      {
        name: '操作',
        width: 300,
        key: 'right',
        classname:'operate',
        formatter: (event) => <Fragment>
                <Button
                  type="primary"
                  size="small"
                  icon="eye"
                  onClick={(e) => {

                    this.setState({
                      editRecord: event.row,
                      infoModal: true,
                    });
                  }
                  }
                >详情
                </Button>
          {
            find(this.permissions, { name: "safe_article_edit" }) &&
              <Fragment>
                <Button
                  type="primary"
                  size="small"
                  icon="edit"
                  onClick={(e) => {
                    this.setState({
                      editRecord: event.row,
                      editModal: true,
                    });
                  }
                  }
                >编辑
                </Button>
                <Button
                  type="danger"
                  size="small"
                  icon="delete"
                  onClick={(e) => {
                    confirm({
                      title: `确定要删除"${event.row.title}"吗?`,
                      content: '请谨慎操作！',
                      okText: '确定',
                      okType: 'danger',
                      cancelText: '取消',
                      centered: true,
                      maskClosable: true,
                      onOk() {
                        that.handleDelete(event.row.id);
                      },
                      onCancel() {
                        console.log('Cancel');
                      },
                    });
                  }
                  }
                >删除
                </Button>
              </Fragment>
          }

        </Fragment>,
      },
    ].map(c => ({  ...defaultColumnProperties,...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if(totalWidth < (gridTableW-210)){
      columns[columns.length - 1].width = columns[columns.length - 1].width + (gridTableW-210) - totalWidth;
    }else{
      columns[columns.length - 1].width = 630;
    }
    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>文章管理</span>
      </div>
      <div className="table-page">
        <div className={'table-data-content'} style={{display:'flex'}}>
          <div style={{width:'200px',height:'auto',background:'#eeeeee',marginRight:'10px'}}>
            {[{id:0,name:'全部板框'},{id:21,name:'首页轮播'},{id:22,name:'安全要闻'},{id:23,name:'政策法规'},{id:24,name:'安全教育'},{id:25,name:'事故通报'},
              {id:26,name:'安全通知'}].map((item,index)=>{
                return  <div onClick={()=>{
                  const {
                    safety_article_manage: { searchParams },
                  } = that.props;
                  that.props.dispatch({
                    type: 'safety_article_manage/changeOneState',
                    payload: {
                      searchParams:{
                        ...searchParams,
                        type:item.id
                      }
                    },
                    callback:()=>{
                      const {
                        safety_article_manage: { searchParams },
                      } = that.props;
                      that.handleSearch({
                        page: 1,
                        ...searchParams
                      });
                    }
                  });
                }} key={index} style={{
                  borderLeft: '5px solid  rgb(2,61,163)'}
                } className={searchParams.type===item.id?styles.item_active:styles.item}>{item.name}</div>
            })}
          </div>
          <div style={{flex:'1'}}>
            <div className="table-condition">{this.renderSimpleForm()}</div>
            <ReactDataGrid
              columns={columns}
              rowGetter={i => {
                return { ...data[i], _index: i };
              }}
              rowsCount={data.length}
              minHeight={tableY}
              rowSelection={{
                showCheckbox: false,
                enableShiftSelect: true,
                selectBy: {
                  indexes: selectedRowKeys,
                },
              }}
              onRowClick={
                (row) => {
                  this.props.dispatch({
                    type: 'safety_article_manage/changeSelectRow',
                    payload: [row],
                  });
                }
              }

            />
            {
              loading&&<Loading />
            }
          </div>

        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Drawer
        title={`发布文章`}
        placement="right"
        keyboard={false}
        maskClosable={false}
        closable={false}
        onClose={() => {

          this.setState({
            addModal: false,
            editRecord: {},
          });
        }}
        width={1000}
        visible={this.state.addModal}
      >
        <AddOrEditMeter
          handleSearch={this.handleSearch}
          onClose={() => {
            this.setState({
              addModal: false,
              editRecord: {},
            });
          }}
          onSave={this.handleAdd}
          wrappedComponentRef={(inst) => this.AddForm = inst}
        />
      </Drawer>
      <Drawer
        title={this.state.editRecord.title}
        placement="right"
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}
        width={1000}
        destroyOnClose
        visible={this.state.infoModal}
      >
        <MailDetail

          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.InfoForm = inst}
        />
      </Drawer>
      <Drawer
        title={this.state.editRecord.title}
        placement="right"
        onClose={() => {
          this.setState({
            editModal: false,
            editRecord: {},
          });
        }}
        width={1000}
        destroyOnClose
        visible={this.state.editModal}
      >
        <AddOrEditMeter
          handleSearch={this.handleSearch}
          onClose={() => {
            this.setState({
              editModal: false,
              editRecord: {},
            });
          }}
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}
        />
      </Drawer>
    </div>;
  }
}

export default BasicList;
